package com.xiake.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiake.utils.JwtHelper;
import com.xiake.utils.Result;
import com.xiake.utils.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginProtectedInterceptor  implements HandlerInterceptor {
    @Autowired
    JwtHelper jwtHelper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中解析出token
        String token = request.getHeader("token");
        //检验是否有效
        boolean expiration = jwtHelper.isExpiration(token);
        //有效放行
       if(!expiration){
           return true;
       }
        //无效返回json结果給前端
        Result result=Result.build(null, ResultCodeEnum.NOTLOGIN);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(result);
        response.getWriter().println(json);
        return false;
    }
}
